package com.sk.weichat.ui.groupchat;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.ApplyInfoBean;
import com.sk.weichat.bean.message.GroupMessage;
import com.sk.weichat.db.dao.GroupMessageDao;
import com.sk.weichat.db.dao.RoomMemberDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.contacts.GroupManagerSetActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.multi.GroupManager;
import com.sk.weichat.ui.message.multi.RoomInfoActivity;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.CustomPopupWindow;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * @Author: chenzl
 * @ClassName: JoinGroupApplyActivity
 * @Description: 加群申请
 * @CreateDate: 2019/9/21 15:43
 */
public class JoinGroupApplyActivity extends BaseActivity implements View.OnClickListener {

    private ImageView imgUserHead;
    private ImageView imgInvitation;
    private TextView tvUserName;
    private TextView tvGroupName;
    private TextView tvApplyTime;
    private TextView tvApplyContent;
    private LinearLayout ll_dispose;
    private TextView tv_dispose_name;
    private TextView tvRefuse;
    private TextView tvSure;

    private String msgId;//进群申请的消息id

    private ApplyInfoBean mApplyInfoBean;
    private RelativeLayout rlApply;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_group_apply);
        msgId = getIntent().getStringExtra("msgId");
        initAction();
        initView();
    }

    private void initAction() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText("加群申请");
    }

    private void initView() {
        imgUserHead = findViewById(R.id.img_user_head);
        imgInvitation = findViewById(R.id.img_invitation);
        tvUserName = findViewById(R.id.tv_user_name);
        tvGroupName = findViewById(R.id.tv_group_name);
        rlApply = findViewById(R.id.rl_apply);
        tvApplyTime = findViewById(R.id.tv_apply_time);
        tvApplyContent = findViewById(R.id.tv_apply_content);
        ll_dispose = findViewById(R.id.ll_dispose);
        tv_dispose_name = findViewById(R.id.tv_dispose_name);
        tvRefuse = findViewById(R.id.tv_refuse);
        tvSure = findViewById(R.id.tv_sure);

        imgInvitation.setOnClickListener(this);
        tvRefuse.setOnClickListener(this);
        tvSure.setOnClickListener(this);
        rlApply.setOnClickListener(this);
        imgUserHead.setOnClickListener(this);
        ll_dispose.setOnClickListener(this);

        getApplyInfo(msgId);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.img_invitation:
                CustomPopupWindow popupWindow = new CustomPopupWindow.Builder(JoinGroupApplyActivity.this)
                        .setView(R.layout.popwindow_invitation)
                        .setWidthAndHeight(ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT)
                        .setAnimationStyle(R.style.pop_anim)
                        .setViewOnclickListener(new CustomPopupWindow.ViewInterface() {
                            @Override
                            public void getChildView(View view, int layoutResId) {
                                TextView tv_one = view.findViewById(R.id.tv_one);
                                TextView tv_two = view.findViewById(R.id.tv_two);
                                tv_two.setVisibility(View.VISIBLE);
                                if (mApplyInfoBean.getAlertMsg().contains(";")) {
                                    String[] all = mApplyInfoBean.getAlertMsg().split(";");
                                    tv_one.setText(all[0]);
                                    tv_two.setText(all[1]);
                                    tv_two.setVisibility(View.VISIBLE);
                                } else {
                                    tv_one.setText(mApplyInfoBean.getAlertMsg());
                                    tv_two.setVisibility(View.GONE);
                                }
                            }
                        })
                        .setOutsideTouchable(true)
                        .create();
                popupWindow.showAsDropDown(v);
                break;
            case R.id.tv_refuse:
                startActivityForResult(new Intent(JoinGroupApplyActivity.this, RefuseInviteActivity.class)
                        .putExtra("VERIFY_MESSAGE_PACKET", msgId)
                        .putExtra("isPersonalInvite", true), 1000);
                break;

            case R.id.tv_sure:
                agreeInvite(msgId);
                break;

            case R.id.rl_apply://点击群名称跳转

//                startActivity(new Intent(JoinGroupApplyActivity.this, OpenGroupInfoActivity.class)
//                        .putExtra("RoomId", mApplyInfoBean.getRoomId())
//                .putExtra("packetId",msgId));
                GroupMessage groupMessage = GroupMessageDao.getInstance().getGroupMessage(coreManager.getSelf().getUserId(),msgId);
                if (groupMessage.getIsGroup()==0){//0在群 ，1不在群里
                    startActivity(new Intent(JoinGroupApplyActivity.this, RoomInfoActivity.class)
                            .putExtra(AppConstant.EXTRA_USER_ID, groupMessage.getUserId())
                            .putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true));
                }else {
                    startActivity(new Intent(JoinGroupApplyActivity.this, OpenGroupInfoActivity.class)
                        .putExtra("RoomId", mApplyInfoBean.getRoomId())
                    .putExtra("packetId",msgId));
                }
                break;
            case R.id.img_user_head:
                intent = new Intent(mContext, PersonalCenterActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, mApplyInfoBean.getUserId());
                mContext.startActivity(intent);
                break;

            case R.id.ll_dispose:
                if (!TextUtils.isEmpty(mApplyInfoBean.getOperatorName())) {
                    intent = new Intent(mContext, PersonalCenterActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, String.valueOf(mApplyInfoBean.getOperator()));
                    mContext.startActivity(intent);
                }
                break;
        }

    }

    /**
     * @author: czl
     * @description 获取个人进群申请详情
     * @date: 2019/9/21 17:37
     */
    private void getApplyInfo(String msgId) {
        DialogHelper.showDefaulteMessageProgressDialog(this);

        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("msgId", msgId);
        HttpUtils.post().url(coreManager.getConfig().ROOM_PERSONAL_INVITE_INFO)
                .params(params).build().execute(new BaseCallback<ApplyInfoBean>(ApplyInfoBean.class) {
            @Override
            public void onResponse(ObjectResult<ApplyInfoBean> result) {
                DialogHelper.dismissProgressDialog();
                if (result.getResultCode() == 1) {
                    mApplyInfoBean = result.getData();
                    AvatarHelper.getInstance().displayAvatar(mApplyInfoBean.getUserId(), imgUserHead);
                    // AlertMsg判断是否为空  为空则并不显示感叹号，不为空则显示
                    if (TextUtils.isEmpty(result.getData().getAlertMsg())){
                        imgInvitation.setVisibility(View.GONE);
                    }else {
                        imgInvitation.setVisibility(View.VISIBLE);
                    }
                    tvUserName.setText(mApplyInfoBean.getNickname());
                    tvGroupName.setText(mApplyInfoBean.getRoomName());
                    tvApplyTime.setText(TimeUtils.getFriendlyTimeDesc(JoinGroupApplyActivity.this, mApplyInfoBean.getCreateTime()));
                    tvApplyContent.setText(mApplyInfoBean.getReason());
                    if (mApplyInfoBean.getRoomIsExist()==1){//群聊存在
                        //状态：0，待处理，1，同意；2，拒绝；3，已经过期;4，已加入
                        switch (mApplyInfoBean.getStatus()) {
                            case 0:
                                ll_dispose.setVisibility(View.GONE);
                                tvRefuse.setVisibility(View.VISIBLE);
                                tvSure.setText("同意");
                                GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(), msgId, 0);////0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                                tvSure.setBackgroundResource(R.drawable.bg_border_btn_blue);
                                tvSure.setEnabled(true);
                                break;
                            case 1:
                                ll_dispose.setVisibility(View.VISIBLE);
                                tv_dispose_name.setText(mApplyInfoBean.getOperatorName());
                                tvRefuse.setVisibility(View.GONE);
                                tvSure.setText("该申请已同意");
                                GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(), msgId, 1);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                                tvSure.setBackgroundResource(R.drawable.bg_border_btn_gray);
                                tvSure.setEnabled(false);
                                break;
                            case 2:
                                ll_dispose.setVisibility(View.VISIBLE);
                                tv_dispose_name.setText(mApplyInfoBean.getOperatorName());
                                tvRefuse.setVisibility(View.GONE);
                                tvSure.setText("该申请已拒绝");
                                GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(), msgId, 2);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                                tvSure.setBackgroundResource(R.drawable.bg_border_btn_gray);
                                tvSure.setEnabled(false);
                                break;
                            case 3:
                                ll_dispose.setVisibility(View.GONE);
                                tvRefuse.setVisibility(View.GONE);
                                tvSure.setText("该申请已过期");
                                GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(), msgId, 3);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                                tvSure.setBackgroundResource(R.drawable.bg_border_btn_gray);
                                tvSure.setEnabled(false);
                                break;
                            case 4:
                                ll_dispose.setVisibility(View.GONE);
                                tvRefuse.setVisibility(View.GONE);
                                tvSure.setText("已加入");
                                if (TextUtils.isEmpty(mApplyInfoBean.getOperatorName())) {
                                    ll_dispose.setVisibility(View.GONE);
                                } else {
                                    ll_dispose.setVisibility(View.VISIBLE);
                                    tv_dispose_name.setText(mApplyInfoBean.getOperatorName());
                                }
                                GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(), msgId, 4);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                                tvSure.setBackgroundResource(R.drawable.bg_border_btn_gray);
                                tvSure.setEnabled(false);
                                break;
                            case 5:
                                ll_dispose.setVisibility(View.GONE);
                                tvRefuse.setVisibility(View.GONE);
                                tvSure.setText("该申请已失效");
                                GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(), msgId, 5);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                                tvSure.setBackgroundResource(R.drawable.bg_border_btn_gray);
                                tvSure.setEnabled(false);
                                break;
                        }
                    }else {//群聊已解散
                        imgUserHead.setEnabled(false);
                        rlApply.setEnabled(false);
                        ll_dispose.setVisibility(View.GONE);
                        tvRefuse.setVisibility(View.GONE);
                        tvSure.setText("该群聊已被解散");
                        GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(), msgId, 5);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                        tvSure.setBackgroundResource(R.drawable.bg_border_btn_gray);
                        tvSure.setEnabled(false);
                    }
                }else {
                    ToastUtil.showToast(JoinGroupApplyActivity.this, result.getResultMsg());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showErrorNet(JoinGroupApplyActivity.this);
            }
        });
    }

    /**
     * @author: czl
     * @description 同意申请进群
     * @date: 2019/9/18 20:54
     */
    private void agreeInvite(String msgId) {
        DialogHelper.showDefaulteMessageProgressDialog(this);

        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("msgId", msgId);
        HttpUtils.post().url(coreManager.getConfig().ROOM_JOIN_AGREE)
                .params(params).build().execute(new BaseCallback<String>(String.class) {

            @Override
            public void onResponse(ObjectResult<String> result) {
                DialogHelper.dismissProgressDialog();
                if (result.getResultCode() == 1) {//同意邀请进群
                    DialogHelper.dismissProgressDialog();
                    //重新获取邀请详情
                    getApplyInfo(msgId);
                    GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(), msgId, 1);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员
                    ToastUtil.showToast(JoinGroupApplyActivity.this,"该申请已同意");
                    return;
                } else if (result.getResultCode() == 1040321) {//已过期
                    ll_dispose.setVisibility(View.GONE);
                    tvRefuse.setVisibility(View.GONE);
                    tvSure.setText("该申请已过期");
                    tvSure.setBackgroundResource(R.drawable.bg_border_btn_gray);
                    tvSure.setEnabled(false);
                    GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(), msgId, 3);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员

                } else if (result.getResultCode() == 1040322) {//已失效
                    ll_dispose.setVisibility(View.GONE);
                    tvRefuse.setVisibility(View.GONE);
                    tvSure.setText("该申请已失效");
                    tvSure.setBackgroundResource(R.drawable.bg_border_btn_gray);
                    tvSure.setEnabled(false);
                    GroupMessageDao.getInstance().updateMsgState(coreManager.getSelf().getUserId(), msgId, 5);//0 未处理 1 同意 2 拒绝 3过期 4已加入 5 失效 6超员

                } else if (result.getResultCode()==1040324||result.getResultCode()==1040325||result.getResultCode()==1040319||result.getResultCode()==1040328){//该申请已经处理 或者 该申请已经拒绝 或者已加入
                    getApplyInfo(msgId);
                }
                ToastUtil.showToast(JoinGroupApplyActivity.this, result.getResultMsg());
            }

            @Override
            public void onError(Call call, Exception e) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showErrorNet(JoinGroupApplyActivity.this);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1000) {
                getApplyInfo(msgId);
                //更新消息内容 与 确认状态
//                String str = message.getContent().replace(getString(R.string.to_confirm), getString(R.string.has_refuse));
//                ChatMessageDao.getInstance().updateMessageContent(mLoginUserId, friendId, packet, str);
//                ChatMessageDao.getInstance().updateGroupVerifyMessageStatus(mLoginUserId, friendId, packet, true);
            }
        }
    }
}
